package com.yxp423.ssmempl.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.yxp423.ssmempl.bean.SysLog;
import com.yxp423.ssmempl.bean.User;
import com.yxp423.ssmempl.bean.dto.UserOnline;
import com.yxp423.ssmempl.service.ISessionService;
import com.yxp423.ssmempl.service.ISysLogService;
import com.yxp423.ssmempl.service.IUserService;
import com.yxp423.ssmempl.service.WebSocketService;
import com.yxp423.ssmempl.utils.base.AjaxResult;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Enumeration;
import java.util.List;

/**
 * @Description: java类作用描述
 * @Author: yxp
 * @CreateDate: 2019-04-16 22:03
 * @Version: 1.0
 */

@Controller
public class LoginController {


	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	ISessionService sessionService;
	@Autowired
	IUserService userService;

	@Autowired
	private ISysLogService sysLogService;

	@Autowired
	private SessionDAO sessionDAO;
	@Autowired
	private WebSocketService webSocket;

	@GetMapping({"/", "loginPage"})
	public String loginPage() {

		return "login";
	}


	@GetMapping("/index")
	public String index() {

		return "index";
	}

//    登录验证

	@GetMapping("/login")
	@ResponseBody
	public AjaxResult login(String userAccount, String password, HttpServletRequest request) {


		AjaxResult result = new AjaxResult();
		String passwordMd5 = SecureUtil.md5(password);

		//获得subject对象
		Subject subject = SecurityUtils.getSubject();

		// 封装前端传来的用户信息，在UserRealm中可调用
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userAccount, passwordMd5);


		//执行登录操作
		try {
			List<UserOnline> onlineUsers = sessionService.getOnlineUsers(request);

			User user = userService.getUserByAccount(userAccount);
			for (UserOnline onlineUser : onlineUsers) {

				boolean isOnline = StrUtil.equals(user.getUserId().toString(), onlineUser.getUserId());

				if (isOnline) {
					result.setSuccess(false);
					result.setMsg("<div>此账号已登录，登录的IP地址为:</div>" +
							"<span style='font-size:20px'><i class='el-icon-location-outline'></i>" + onlineUser.getHost() + "</span>" +
							"<div>登录时间为:</div>" +
							"<div style='font-size:20px'><i class='el-icon-alarm-clock'></i>" + DateUtil.formatDateTime(onlineUser.getStartTimestamp()) + "</div>");
					return result;
				}
			}

			//登陆成功
			subject.login(usernamePasswordToken);



			SysLog sysLog = new SysLog();


			User currentUser = (User) subject.getPrincipal();
			sysLog.setUserId(currentUser.getUserId().toString());
			sysLog.setUserName(currentUser.getName());
			sysLog.setIpAddress(NetUtil.getLocalhostStr());
			sysLog.setLogTime(DateUtil.date());
			Enumeration<String> headerNames = request.getHeaderNames();
			String userAgent = request.getHeader("user-agent");

			sysLog.setLogType(SysLog.LOGIN);
			sysLogService.saveLog(sysLog);

			result.setSuccess(true);
			result.setMsg("登陆成功");

		} catch (UnknownAccountException e) { //UnknownAccountException 无此用户名异常

			result.setSuccess(false);
			result.setMsg("帐户不存在");

		} catch (IncorrectCredentialsException e) {
			result.setSuccess(false);
			result.setMsg("密码错误");

		} catch (LockedAccountException e) {
			result.setSuccess(false);
			result.setMsg("账号已被冻结");

		} catch (AuthenticationException e) {//AuthenticationException:认证异常
			e.printStackTrace();
		} catch (NullPointerException e) {

			logger.error("当前没有在线");
		}


		return result;
	}


	@GetMapping("/logout")
	@ResponseBody
	public AjaxResult logout() {

		AjaxResult result = new AjaxResult();
		Subject subject = SecurityUtils.getSubject();

		try {

			User user = (User) SecurityUtils.getSubject().getPrincipal();

			if (ObjectUtil.isEmpty(user)) {
				result.setSuccess(false);
				result.setMsg("用户未在登录状态");

			} else {

				SysLog sysLog = new SysLog();
				User currentUser = (User) subject.getPrincipal();
				sysLog.setUserId(currentUser.getUserId().toString());
				sysLog.setUserName(currentUser.getName());
				sysLog.setIpAddress(NetUtil.getLocalhostStr());
				sysLog.setLogTime(DateUtil.date());
				sysLog.setLogType(SysLog.LOGOUT);
				sysLogService.saveLog(sysLog);

				//注销
				subject.logout();

				result.setSuccess(true);
				result.setMsg("退出成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
}
